import reqwest from "reqwest"
import Immutable from "Immutable"
export const FETCH_CITYS = 'FETCH_CITYS'
export const FETCH_COMMS = 'FETCH_COMMS'
export const FETCH_DISTRICTS = 'FETCH_DISTRICTS'


export function fetchCitys(){
  return (dispatch)=>{
    reqwest({
      url:"/api/findCity"
    }).then(data=>dispatch({
      type:FETCH_CITYS,
      citys:Immutable.fromJS(data.data.map((city)=>({
        id:city.id,
        name:city.name
      })))
    }))
  }
}

export function fetchDistricts(id){
  return (dispatch)=>{
    reqwest({
      url:"api/findArea/"+id
    }).then(data=>dispatch({
      type:FETCH_DISTRICTS,
      districts:Immutable.fromJS(data.data.map((district)=>({
        id:district.id,
        name:district.name,
        cityId:id
      })))
    }))
  }
}


export function fetchDistrictsIfNeed(id){
  return (dispatch,getState)=>{
    const first =getState().getIn(["city","districts"]).find((district)=>district.get("cityId")===id)
    console.log(first);
    if(first===undefined){
      dispatch(fetchDistricts(id))
    }


  }



}


export function fetchCitysIfNeed(){
  return (dispatch,getState)=>{
    if(getState().getIn(["city","citys"])){
      dispatch(fetchCitys())
    }
  }
}
